package com.qipay.sp.excutor.fuhuipay;

import com.qipay.core.utils.CommUtil;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 付汇自带的加密工具
 * @author xinnian
 * 
 */
public class FHSignUtils {

	/***
	 * 验证签名
	 * 
	 * @param params
	 * @return
	 */
	public static boolean checkSign(Map<String, String> params, String signKey) {
		String sign = params.get("sign");

		if (sign == null || "".equals(sign)) {

			return false;
		}

		SortedMap<String, String> sortedMap = new TreeMap<String, String>(
				params);

		StringBuilder toSign = new StringBuilder();
		for (String key : sortedMap.keySet()) {
			String value = params.get(key);
			if (CommUtil.isNotEmpty(value) && !"sign".equals(key)) {
				toSign.append(key + "=" + value + "&");
			}
		}

		toSign.append("key=" + signKey);

		String checkSign = DigestUtils.md5Hex(toSign.toString()).toUpperCase();

		if (!checkSign.equals(sign)) {
			return false;
		}

		return true;
	}

	/**
	 * 签名
	 * 
	 * @param params
	 * @param signKey
	 * @return
	 */
	public static String createSign(Map<String, String> params, String signKey) {

		String result = null;

		SortedMap<String, String> sortedMap = new TreeMap<String, String>(
				params);

		StringBuilder toSign = new StringBuilder();
		for (String key : sortedMap.keySet()) {
			String value = params.get(key);
			if (CommUtil.isNotEmpty(value) && !"sign".equals(key)) {
				toSign.append(key + "=" + value + "&");
			}
		}

		toSign.append("key=" + signKey);

		result = DigestUtils.md5Hex(toSign.toString()).toUpperCase();
		return result;
	}

}
